package buru.budu;

import com.alibaba.fastjson.JSONObject;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.*;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.Map;

/**
 * Auth: bruce-sha
 * Date: 2015/3/27
 * https://github.com/springside/springside4/blob/ed3a7f44bbdcf00a61228268537607e572c83482/modules/core/src/test/java/org/springside/modules/test/jetty/JettyFactory.java
 * <p/>
 * java -cp.:servlet-api-2.5.jar:jetty-all-$JETTY_VERSION.jar JettyBoot
 *
 * 例子 http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded
 * 8的wiki https://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty
 *
 * http://blog.csdn.net/kongxx/article/category/1068538
 *
 */
public class JettyBoot {

    public static void main(String[] args) throws Exception {
//        simplest();
        some();
//        jersey();
    }


    @Path("/hello")
    public static class JobService {
        @GET
        public Response list() {
            return Response.ok("Hello World!" + System.currentTimeMillis()).build();
        }
    }

    static void jersey() throws Exception {

        final Server _server = new Server();

        ServerConnector _connector = new ServerConnector(_server);
        _connector.setPort(8080);
        _connector.setReuseAddress(false);
        _server.setConnectors(new Connector[]{_connector});

        //可以创建两个connecter，也可以创建两个context
        ServletContextHandler _servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        _servletHandler.setContextPath("/");
        _server.setHandler(_servletHandler);
//        _servletHandler.setClassLoader(Thread.currentThread().getContextClassLoader());

        ResourceHandler _resourceHandler = new ResourceHandler();
        _resourceHandler.setDirectoriesListed(true);
        _resourceHandler.setWelcomeFiles(new String[]{"index.html"});
        _resourceHandler.setResourceBase("src/main/webapp/");
        _server.insertHandler(_resourceHandler);


        _server.insertHandler(new ParamHandler());

//必须放最后，依次执行 HandlerCollection才是必须执行 看HandlerList的区别 http://ipjmc.iteye.com/blog/1839999
       final StatisticsHandler _statisticsHandler=new StatisticsHandler();
        _server.insertHandler(_statisticsHandler);

        new Thread(){
            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(1000*10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(_statisticsHandler.toStatsHTML());
                }
            }
        }.start();

        // Prepare rest service servlet
        ServletHolder _jersey = new ServletHolder(new ServletContainer(new ResourceConfig(JobService.class)));
        _jersey.setName("restful service servlet");

        _servletHandler.addServlet(_jersey, "/rest/*");
        // http://localhost:8080/hello
        _servletHandler.addServlet(new ServletHolder(new IndexServlet()), "/index");
//        _servletHandler.addFilter()
//        _server.setHandler(new HelloWorld());

//        HandlerCollection collection = new HandlerCollection();
//        RequestLogHandler rlh = new RequestLogHandler();
//        // Slf4j - who uses anything else?
//        Slf4jRequestLog requestLog = new Slf4jRequestLog();
//        requestLog.setExtended(false);
//        rlh.setRequestLog(requestLog);
//        collection.setHandlers(new Handler[] {  rlh });
//        _server.setHandler(collection);


        _server.setStopAtShutdown(true);

        //启动服务
        _server.start();
        _server.join();
    }

    static class ParamHandler extends HandlerWrapper {
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            Map params = request.getParameterMap();
            if (params.size() > 0) {
                response.setContentType("text/plain");
                response.getWriter().println(new JSONObject(params));
                ((Request) request).setHandled(true);
            }else{
                super.handle(target,baseRequest,request,response);
            }
        }
    }

    static class IndexServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        private String msg = "Hello World!";

        public IndexServlet() {
        }

        public IndexServlet(String msg) {
            this.msg = msg;
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println("<h1>" + msg + "</h1>");
            response.getWriter().println("session=" + request.getSession(true).getId());
        }
    }

    static void some() throws Exception {
        final Server server = new Server();

        ServerConnector c1 = new ServerConnector(server);
        c1.setPort(8080);
        ServerConnector c2 = new ServerConnector(server);
        c2.setPort(9090);

        c1.setReuseAddress(false);

        server.setConnectors(new Connector[]{c1, c2});


        //设置根路径
        WebAppContext context = new WebAppContext("src/main/webapp", "/web");

//        context.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH);

        server.setHandler(context);
        server.setStopAtShutdown(true);

        //启动服务
        server.start();
        server.join();
    }

    static void simplest() throws Exception {
        final Server server = new Server(8080);


        server.setHandler(new HelloHandler());

        Connector[] c = server.getConnectors();
        System.out.println(c);

        server.start();
        server.join();


    }

    static class HelloHandler extends AbstractHandler {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("<h1>Hello World</h1>");
        }
    }
}
